import { useEffect, useRef, useState } from 'react'

export function useAutoScroll<T extends HTMLElement>() {
  const containerRef = useRef<T>(null)
  const bottomRef = useRef<HTMLDivElement>(null)
  const lastItemRef = useRef<HTMLDivElement | null>(null)
  const [isBottomVisible, setIsBottomVisible] = useState(true)
  const [isAllow, setIsAllow] = useState(true)

  // 监听底部可见性
  useEffect(() => {
    if (!containerRef.current || !bottomRef.current) return
    const observer = new IntersectionObserver(
      ([entry]) => {
        const boolean = !entry.isIntersecting
        setIsBottomVisible(boolean)
        if (entry.isIntersecting) {
          setIsAllow(true) // 用户滚动到底部，恢复自动滚动权限
        }
      },
      {
        root: containerRef.current,
        threshold: 1.0,
      }
    )
    observer.observe(bottomRef.current)
    return () => observer.disconnect()
  }, [])

  // 滚动到底部（受 isAllow 限制）
  const scrollToBottom = () => {
    if (containerRef.current && isAllow) {
      containerRef.current.scrollTo({
        top: containerRef.current.scrollHeight,
        behavior: 'smooth',
      })
    }
  }
  useEffect(() => {
    if (!isBottomVisible) {
      scrollToBottom()
    }
  }, [isAllow, isBottomVisible])
  useEffect(() => {
    if (isAllow) {
      scrollToBottom()
    }
  }, [isAllow])
  const setIsAllowFn = (value: boolean) => {
    setIsAllow(value)
  }
  return {
    containerRef,
    bottomRef,
    scrollToBottom,
    isBottomVisible,
    lastItemRef,
    isAllow,
    setIsAllow: setIsAllowFn,
  }
}
